<template>
  <div class="caregiver-messages">
    <div class="header">
      <h2>消息中心</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCompose">发送消息</el-button>
        <el-button @click="handleRefresh">刷新</el-button>
      </div>
    </div>

    <!-- 消息类型筛选 -->
    <div class="filter-container">
      <el-radio-group v-model="messageType" @change="handleTypeChange">
        <el-radio-button label="all">全部消息</el-radio-button>
        <el-radio-button label="unread">未读消息</el-radio-button>
        <el-radio-button label="read">已读消息</el-radio-button>
      </el-radio-group>
      
      <el-select
        v-model="priorityFilter"
        placeholder="优先级筛选"
        style="margin-left: 20px; width: 120px"
        @change="handleSearch"
      >
        <el-option label="全部优先级" value="" />
        <el-option label="紧急" value="URGENT" />
        <el-option label="高" value="HIGH" />
        <el-option label="普通" value="NORMAL" />
        <el-option label="低" value="LOW" />
      </el-select>
    </div>

    <!-- 消息列表 -->
    <div class="message-list">
      <div
        v-for="message in messageList"
        :key="message.messageId"
        :class="['message-item', { unread: !message.isRead, urgent: message.priority === 'URGENT' }]"
        @click="handleViewMessage(message)"
      >
        <div class="message-header">
          <div class="message-title">
            <span class="priority-tag" :class="message.priority?.toLowerCase()">
              {{ getPriorityText(message.priority) }}
            </span>
            <span class="title-text">{{ message.title }}</span>
            <el-tag v-if="!message.isRead" size="small" type="danger">未读</el-tag>
          </div>
          <div class="message-time">
            {{ formatDateTime(message.createTime) }}
          </div>
        </div>
        
        <div class="message-content">
          <p class="content-preview">{{ message.content }}</p>
        </div>
        
        <div class="message-footer">
          <div class="sender-info">
            <span class="sender-type">{{ getSenderTypeText(message.senderType) }}</span>
            <span class="sender-name">{{ message.senderName }}</span>
          </div>
          <div class="message-actions">
            <el-button
              v-if="!message.isRead"
              type="primary"
              link
              size="small"
              @click.stop="handleMarkAsRead(message)"
            >
              标记为已读
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click.stop="handleDeleteMessage(message)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="messageList.length === 0" class="empty-state">
        <el-empty description="暂无消息" />
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 消息详情对话框 -->
    <el-dialog
      title="消息详情"
      v-model="detailDialogVisible"
      width="600px"
    >
      <div class="message-detail">
        <div class="detail-header">
          <h3>{{ currentMessage.title }}</h3>
          <div class="detail-meta">
            <span class="sender">发件人: {{ currentMessage.senderName }} ({{ getSenderTypeText(currentMessage.senderType) }})</span>
            <span class="time">时间: {{ formatDateTime(currentMessage.createTime) }}</span>
            <el-tag :type="getPriorityTagType(currentMessage.priority)">
              {{ getPriorityText(currentMessage.priority) }}
            </el-tag>
          </div>
        </div>
        
        <div class="detail-content">
          <p>{{ currentMessage.content }}</p>
        </div>
        
        <div v-if="currentMessage.relatedElderId" class="related-info">
          <el-divider content-position="left">关联信息</el-divider>
          <p>关联老人ID: {{ currentMessage.relatedElderId }}</p>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button
          v-if="!currentMessage.isRead"
          type="primary"
          @click="handleMarkCurrentAsRead"
        >
          标记为已读
        </el-button>
        <el-button
          type="primary"
          @click="handleReply"
        >
          回复
        </el-button>
      </template>
    </el-dialog>

    <!-- 发送消息对话框 -->
    <el-dialog
      title="发送消息"
      v-model="composeDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="composeFormRef"
        :model="composeForm"
        :rules="composeRules"
        label-width="80px"
      >
        <el-form-item label="收件人" prop="receiverType">
          <el-radio-group v-model="composeForm.receiverType">
            <el-radio label="family">家属</el-radio>
            <el-radio label="reception">前台</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="composeForm.receiverType === 'family'" label="选择家属" prop="receiverId">
          <el-select
            v-model="composeForm.receiverId"
            placeholder="请选择家属"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="family in familyList"
              :key="family.familyId"
              :label="`${family.name} (${family.phone})`"
              :value="family.familyId"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="composeForm.priority" placeholder="请选择优先级">
            <el-option label="普通" value="NORMAL" />
            <el-option label="高" value="HIGH" />
            <el-option label="紧急" value="URGENT" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="composeForm.title"
            placeholder="请输入消息标题"
          />
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="composeForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入消息内容"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="关联老人">
          <el-select
            v-model="composeForm.relatedElderId"
            placeholder="选择关联老人（可选）"
            style="width: 100%"
          >
            <el-option
              v-for="elder in elderList"
              :key="elder.elderId"
              :label="elder.name"
              :value="elder.elderId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="composeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSendMessage" :loading="sending">
          发送
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMyElders } from '@/api/elder.js'
import { getFamilyList } from '@/api/family.js'
import { 
  getCaregiverMessages, 
  markMessageAsRead, 
  deleteMessage, 
  sendMessage 
} from '@/api/message.js'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const composeDialogVisible = ref(false)
const sending = ref(false)
const composeFormRef = ref()

// 数据列表
const messageList = ref([])
const elderList = ref([])
const familyList = ref([])

// 筛选条件
const messageType = ref('all')
const priorityFilter = ref('')

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 当前查看的消息
const currentMessage = ref({})

// 发送消息表单
const composeForm = reactive({
  receiverType: 'family',
  receiverId: '',
  title: '',
  content: '',
  priority: 'NORMAL',
  relatedElderId: ''
})

// 表单验证规则
const composeRules = {
  receiverType: [{ required: true, message: '请选择收件人类型', trigger: 'change' }],
  receiverId: [{ required: true, message: '请选择收件人', trigger: 'change' }],
  title: [{ required: true, message: '请输入消息标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入消息内容', trigger: 'blur' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }]
}

// 初始化数据
onMounted(() => {
  loadMessageList()
  loadElderList()
  loadFamilyList()
})

// 加载消息列表
const loadMessageList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      messageType: messageType.value,
      priority: priorityFilter.value
    }
    
    const response = await getCaregiverMessages(params)
    messageList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载消息列表失败:', error)
    ElMessage.error('加载消息列表失败')
  } finally {
    loading.value = false
  }
}

// 加载老人列表
const loadElderList = async () => {
  try {
    const response = await getMyElders()
    elderList.value = response.data || []
  } catch (error) {
    console.error('加载老人列表失败:', error)
  }
}

// 加载家属列表
const loadFamilyList = async () => {
  try {
    const response = await getFamilyList()
    familyList.value = response.data || []
  } catch (error) {
    console.error('加载家属列表失败:', error)
  }
}

// 消息类型变化
const handleTypeChange = () => {
  pagination.currentPage = 1
  loadMessageList()
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadMessageList()
}

// 刷新
const handleRefresh = () => {
  loadMessageList()
}

// 查看消息详情
const handleViewMessage = async (message) => {
  currentMessage.value = message
  detailDialogVisible.value = true
  
  // 如果消息未读，标记为已读
  if (!message.isRead) {
    await handleMarkAsRead(message)
  }
}

// 标记消息为已读
const handleMarkAsRead = async (message) => {
  try {
    await markMessageAsRead(message.messageId)
    message.isRead = true
    ElMessage.success('标记为已读')
  } catch (error) {
    console.error('标记为已读失败:', error)
    ElMessage.error('标记为已读失败')
  }
}

// 标记当前消息为已读
const handleMarkCurrentAsRead = async () => {
  await handleMarkAsRead(currentMessage.value)
}

// 删除消息
const handleDeleteMessage = async (message) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
      type: 'warning'
    })
    
    await deleteMessage(message.messageId)
    ElMessage.success('删除成功')
    loadMessageList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 打开发送消息对话框
const handleCompose = () => {
  Object.assign(composeForm, {
    receiverType: 'family',
    receiverId: '',
    title: '',
    content: '',
    priority: 'NORMAL',
    relatedElderId: ''
  })
  composeDialogVisible.value = true
}

// 发送消息
const handleSendMessage = async () => {
  if (!composeFormRef.value) return
  
  try {
    await composeFormRef.value.validate()
    sending.value = true
    
    const messageData = {
      ...composeForm,
      receiverType: composeForm.receiverType.toUpperCase()
    }
    
    await sendMessage(messageData)
    ElMessage.success('发送成功')
    composeDialogVisible.value = false
    loadMessageList()
  } catch (error) {
    console.error('发送失败:', error)
    if (error.errors) {
      ElMessage.error('请检查表单填写是否正确')
    } else {
      ElMessage.error('发送失败')
    }
  } finally {
    sending.value = false
  }
}

// 回复消息
const handleReply = () => {
  composeDialogVisible.value = true
  // 可以在这里预设回复内容
  composeForm.title = `回复: ${currentMessage.value.title}`
  composeForm.receiverType = currentMessage.value.senderType.toLowerCase()
  // 需要根据消息类型设置收件人ID
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadMessageList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadMessageList()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取优先级文本
const getPriorityText = (priority) => {
  const priorityMap = {
    'URGENT': '紧急',
    'HIGH': '高',
    'NORMAL': '普通',
    'LOW': '低'
  }
  return priorityMap[priority] || '普通'
}

// 获取优先级标签类型
const getPriorityTagType = (priority) => {
  const typeMap = {
    'URGENT': 'danger',
    'HIGH': 'warning',
    'NORMAL': 'info',
    'LOW': 'success'
  }
  return typeMap[priority] || 'info'
}

// 获取发件人类型文本
const getSenderTypeText = (senderType) => {
  const typeMap = {
    'FAMILY': '家属',
    'RECEPTION': '前台',
    'ADMIN': '管理员',
    'CAREGIVER': '护工'
  }
  return typeMap[senderType] || '未知'
}
</script>

<style scoped>
.caregiver-messages {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.message-list {
  min-height: 400px;
}

.message-item {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.message-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.message-item.unread {
  background: #f0f9ff;
  border-left: 4px solid #409eff;
}

.message-item.urgent {
  border-left: 4px solid #f56c6c;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.message-title {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.priority-tag {
  padding: 2px 6px;
  border-radius: 2px;
  font-size: 12px;
  color: white;
}

.priority-tag.urgent {
  background: #f56c6c;
}

.priority-tag.high {
  background: #e6a23c;
}

.priority-tag.normal {
  background: #409eff;
}

.priority-tag.low {
  background: #67c23a;
}

.title-text {
  font-weight: 600;
  flex: 1;
}

.message-time {
  color: #909399;
  font-size: 12px;
}

.message-content {
  margin-bottom: 12px;
}

.content-preview {
  color: #606266;
  line-height: 1.5;
  margin: 0;
}

.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.sender-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sender-type {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 2px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.message-detail {
  padding: 0 10px;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 18px;
}

.detail-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.detail-content {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.detail-content p {
  margin: 0;
  line-height: 1.6;
  color: #303133;
}

.related-info {
  font-size: 14px;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .caregiver-messages {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .filter-container {
    padding: 12px;
  }
  
  .message-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .message-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .message-actions {
    align-self: flex-end;
  }
}
